﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using PccCommonForC;

public partial class Manager_OrderApp_BasketApp : System.Web.UI.Page
{
    int pQuantity = 0;
    decimal pTotal = 0;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["arrOPd"] == null)
        {
            ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script>alert('Đơn hàng đã không cập nhật quá thời gian qui định. Vui lòng chọn lại đơn hàng khác')</script>");
            Response.Redirect("OrderApp.aspx");

        }
        if (!IsPostBack)
        {
            BindData();
            //cap nhat session
            UpdateBasket();
        }


    }

    private void UpdateBasket()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("PDID");
        dt.Columns.Add("PDName");
        dt.Columns.Add("Quantity");
        dt.Columns.Add("Price");
        dt.Columns.Add("Rate");
        dt.Columns.Add("KindNo");
        dt.Columns.Add("DiscountPrice");
        dt.Columns.Add("Total");
        dt.Columns.Add("NoteDetail");

        dt.Columns.Add("Repaid");
        dt.Columns.Add("PayMoney");
        dt.Columns.Add("RemainPrice");
        dt.Columns.Add("Note");

        for (int i = 0; i < grv_Master.Rows.Count; i++)
        {
            Label lblMaSP = (Label)grv_Master.Rows[i].FindControl("lblMaSP");
            Label lblTenSP = (Label)grv_Master.Rows[i].FindControl("lblTenSP");
            TextBox txtSoLuong = (TextBox)grv_Master.Rows[i].FindControl("txtSoLuong");
            Label lblDonGia = (Label)grv_Master.Rows[i].FindControl("lblDonGia");
            Label lblRate = (Label)grv_Master.Rows[i].FindControl("lblRate");
            HtmlInputHidden hidKindNo = (HtmlInputHidden)grv_Master.Rows[i].FindControl("hidKindNo");
            TextBox txtSaleOfPrice = (TextBox)grv_Master.Rows[i].FindControl("txtSaleOfPrice");
            TextBox txtPrepaid = (TextBox)grv_Master.Rows[i].FindControl("txtPrepaid");
            TextBox lblTotal = (TextBox)grv_Master.Rows[i].FindControl("lblTotal");
            TextBox txtNoteDetail = (TextBox)grv_Master.Rows[i].FindControl("txtNoteDetail");
            if (IsNotOrderDel(lblMaSP.Text.Trim()))
            {
                DataRow dr = dt.NewRow();
                dr[0] = lblMaSP.Text;
                dr[1] = lblTenSP.Text;
                dr[2] = txtSoLuong.Text;

                dr[3] = lblDonGia.Text;
                dr[4] = lblRate.Text;
                dr[6] = txtSaleOfPrice.Text;
                dr[7] = lblTotal.Text;
                dr[9] = txtRepaid.Text;
                dr[10] = txtPaidMoney.Text;
                dr[11] = txtRemainPrice.Text;

                dr[5] = hidKindNo.Value;
                dr[8] = txtNoteDetail.Text;


                dr[12] = txtNote.Text;
                dt.Rows.Add(dr);
            }

        }
        Session["dtBasketAdmin"] = dt;
    }

    private bool IsNotOrderDel(string OrderID)
    {
        string strDelOrderID = hidOrderDelete.Value;
        if (strDelOrderID.Length > 0)
        {
            strDelOrderID = hidOrderDelete.Value.Substring(0, hidOrderDelete.Value.Length - 1);
            string[] ArrDelOrder = strDelOrderID.Split(',');
            for (int i = 0; i < ArrDelOrder.Length; i++)
            {
                if (OrderID.Trim() == ArrDelOrder[i].Trim())
                {
                    return false;
                }
            }
        }
        return true;



    }

    private void BindData()
    {

        DataTable dt = GetData();

        grv_Master.DataSource = dt;
        grv_Master.DataBind();
        if (dt.Rows.Count > 0)
        {
            if (Session["dtBasketAdmin"] != null)//Lay du lieu tu datattable Session["dtBasketAdmin"]
            {
                lblTongsotien.Text = FormatMoney(pTotal.ToString());
                lblQuantity.Text = pQuantity.ToString();
                txtRemainPrice.Text = FormatMoney(dt.Rows[0]["RemainPrice"].ToString());
                txtPaidMoney.Text = "0";
                txtRepaid.Text = FormatMoney(dt.Rows[0]["Repaid"].ToString());
                txtNote.Text = dt.Rows[0]["Note"].ToString();

                hidRemainPrice.Value = dt.Rows[0]["RemainPrice"].ToString();
                hidRepaid.Value = dt.Rows[0]["Repaid"].ToString();

            }
            else
            {
                lblTongsotien.Text = FormatMoney(pTotal.ToString());
                lblQuantity.Text = pQuantity.ToString();
                txtRemainPrice.Text = FormatMoney(pTotal);
                txtPaidMoney.Text = "0";
                hidRemainPrice.Value = pTotal.ToString();
                hidRepaid.Value = "0";
                txtRepaid.Text = "0";

            }
            if (txtRemainPrice.Text == "0")
            {
                tblPaymoney.Attributes.CssStyle.Add("display", "none");

                chkPayment.Checked = true;
            }

        }



    }



    private DataTable GetData()
    {
        clsWebShop cls = new clsWebShop();
        lblUSD.Text = "Tỉ giá USD: " + FormatMoney(cls.GetMoney("USD")) + " VNĐ";
        hidUSD.Value = cls.GetMoney("USD").ToString();

        DataTable dt = new DataTable();
        if (Session["dtBasketAdmin"] != null)
        {
            dt = (DataTable)Session["dtBasketAdmin"];
        }
        else
        {

            //Lay so luong trong kho
            Session["dtCountStore"] = cls.Get_QuantityStoreGroup("", "0").Tables[0];
            //Lay so san pham
            string sOPd = "";
            ArrayList arrOPd = (ArrayList)Session["arrOPd"];
            for (int i = 0; i < arrOPd.Count; i++)
                sOPd += "'" + arrOPd[i].ToString() + "',";
            sOPd = sOPd.Substring(0, sOPd.Length - 1);


            /*string sql = "select pd.PDID,pd.PDName,1 Quantity,pd.DiscountPrice,pd.Rate,pd.Price,cat.KindNo,0 Repaid,0 PayMoney,0 RemainPrice,'' NoteDetail,";
            sql += " Total=case ";
            sql += " when rate='USD' then price * " + hidUSD.Value + "";
            sql += " else price";
            sql += " end";

            sql += " from product pd inner join Catalogue  cat on cat.CatID=pd.CatID	where  pd.PDID in (" + sOPd + ")";
            */

            string sql = "   select pd.PDID,pd.PDName,1 Quantity,pd.IsSaleOf,pd.DiscountPrice,pd.Rate,pd.Price,cat.KindNo,0 Repaid,0     PayMoney,0 RemainPrice,'' NoteDetail,";
            sql += "  Total=case ";
            sql += " when rate='USD' and IsSaleOf='Y'  then DiscountPrice *  " + hidUSD.Value + "";
            sql += " when rate='USD' and IsSaleOf='N'  then Price *  " + hidUSD.Value + "";
            sql += " when rate=N'VNĐ' and IsSaleOf='Y'  then DiscountPrice ";
            sql += " else price";
            sql += " end";
            sql += " from product pd inner join Catalogue  cat on cat.CatID=pd.CatID	where  pd.PDID in (" + sOPd + ")";




            dt = cls.GetData(sql).Tables[0];
        }

        return dt;

    }

    protected void grv_Master_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {

        DataTable dt = new DataTable();
        UpdateBasket();
        dt = (DataTable)Session["dtBasketAdmin"];
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            if (grv_Master.DataKeys[e.RowIndex].Value.ToString() == dt.Rows[i]["PDID"].ToString())
            {
                dt.Rows[i].Delete();
            }
        }

        Session["dtBasketAdmin"] = dt;
        BindData();
    }
    protected void grv_Master_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Label lblSL = (Label)e.Row.FindControl("lblSL");
            Label lblRate = (Label)e.Row.FindControl("lblRate");
            TextBox lblTotal = (TextBox)e.Row.FindControl("lblTotal");
            Label lblDonGia = (Label)e.Row.FindControl("lblDonGia");
            TextBox lblRemainPrice = (TextBox)e.Row.FindControl("lblRemainPrice");
            TextBox txtSoLuong = (TextBox)e.Row.FindControl("txtSoLuong");
            TextBox txtSaleOfPrice = (TextBox)e.Row.FindControl("txtSaleOfPrice");

            string KindNo = DataBinder.Eval(e.Row.DataItem, "KindNo").ToString();
            if (KindNo != "P")
            {
                e.Row.Cells[8].Text = "<font color='red'>Free</font>";
                txtSoLuong.ReadOnly = true;
                txtSoLuong.BackColor = System.Drawing.Color.FromName("#eaeaea");
                e.Row.Cells[8].BackColor = System.Drawing.Color.LightYellow;
                lblDonGia.Text = "0";
                lblTotal.Text = "0";
                txtSaleOfPrice.Text = "0";

                txtSaleOfPrice.ReadOnly = true;
                txtSaleOfPrice.BackColor = System.Drawing.Color.FromName("#eaeaea");

            }
            else
            {

                if (txtSaleOfPrice.Text != "0")
                {
                    txtSaleOfPrice.Text = FormatMoney(txtSaleOfPrice.Text);
                    /*
                    decimal totaleach = ConvertToDecimal(txtSaleOfPrice.Text.Replace(",", "")) * ConvertToInt(txtSoLuong.Text);
                    lblTotal.Text = totaleach.ToString();*/
                }

                pTotal += decimal.Parse(lblTotal.Text.Replace(",", ""));
                pQuantity += int.Parse(txtSoLuong.Text);
                lblDonGia.Text = FormatMoney(lblDonGia.Text);
                lblTotal.Text = FormatMoney(lblTotal.Text);
            }
            try
            {
                if (KindNo == "P")
                {

                    string sQ_Store = "0";
                    try
                    {
                        DataTable dt = (DataTable)Session["dtCountStore"];
                        sQ_Store = dt.Select(" PDID='" + DataBinder.Eval(e.Row.DataItem, "PDID").ToString() + "'")[0]["Quantity_Store"].ToString();
                    }
                    catch
                    {
                        sQ_Store = "0";
                    }
                    lblSL.Text = sQ_Store;
                    if (int.Parse(lblSL.Text) <= 0)
                    {
                        txtSoLuong.ReadOnly = true;
                        txtSoLuong.BackColor = System.Drawing.Color.Orange;
                    }
                }
            }
            catch { }
        }
        /*else if (e.Row.RowType == DataControlRowType.Footer)
        {
            Label lblsl = new Label();
            Label lbltt = new Label();
            Label lblVND = new Label();
            lblsl.ID = "lblSL";
            lblsl.Text = pQuantity.ToString();
            lbltt.ID = "lblTT";
            lbltt.Text = FormatMoney(pTotal.ToString());
            lblVND.Text = "<b>$ </b>";
            e.Row.Cells[0].Text = "<b>Tổng cộng</b>";
            e.Row.Cells[0].ColumnSpan = 3;
            e.Row.Cells[4].Controls.Add(lblsl);
            e.Row.Cells[5].Text = "";
            e.Row.Cells[5].ColumnSpan = 4;
            e.Row.Cells[6].Controls.Add(lblVND);
            e.Row.Cells[6].Controls.Add(lbltt);
            e.Row.Cells[0].HorizontalAlign = HorizontalAlign.Left;
            e.Row.Cells[4].HorizontalAlign = HorizontalAlign.Center;
            e.Row.Cells[6].HorizontalAlign = HorizontalAlign.Right;

            //e.Row.Cells(0).CssClass = "cssBorderGrv";
            //e.Row.Cells(5).CssClass = "cssBorderGrv";
            //e.Row.Cells(6).CssClass = "cssBorderGrv";
            //e.Row.Cells(4).CssClass = "cssBorderGrv";

            e.Row.Cells.RemoveAt(1);
            e.Row.Cells.RemoveAt(1);
            e.Row.Cells.RemoveAt(1);
            e.Row.Cells.RemoveAt(4);
            e.Row.Cells.RemoveAt(4);
           // e.Row.Cells.RemoveAt();
        }*/
    }

    private int ConvertToInt(string Quantity)
    {
        int dQuantity = 0;
        try
        {
            dQuantity = int.Parse(Quantity);
        }
        catch
        {
            ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script>alert('Số lượng không hợp lệ')</script>");

        }
        return dQuantity;
    }

    private decimal ConvertToDecimal(string value)
    {
        decimal dReturn = 0;
        try
        {
            if (value != "" && value != null)
                dReturn = decimal.Parse(value);
        }
        catch { Exception ex; }
        return dReturn;
    }

    private string FormatMoney(string sNum)
    {
        string sReturn = "0";
        try
        {
            sReturn = string.Format("{0:###,###,##0}", decimal.Parse(sNum));
        }
        catch (Exception) { }
        return sReturn;
    }
    private string FormatMoney(decimal dNum)
    {
        string sReturn = "0";
        try
        {
            sReturn = string.Format("{0:###,###,##0}", dNum);
        }
        catch (Exception) { }
        return sReturn;
    }
    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        UpdateBasket();
        BindData();
    }
    protected void btnBack_Click(object sender, EventArgs e)
    {
        Response.Redirect("OrderApp.aspx?CodeID=" + Request.QueryString["CodeID"] + "&Status=N");
    }
    protected void btnOrder_Click(object sender, EventArgs e)
    {

        UpdateBasket();
        Response.Redirect("OrderDetailApp.aspx?CodeID=" + Request.QueryString["CodeID"]);
    }
}
